﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Models;
using DevExpress.XtraRichEdit.API.Word;
using System.Threading;
using ChinaDynastyTours.Helpers;

namespace ChinaDynastyTours.Views
{
    public partial class GuideArrangeForm : DevExpress.XtraEditors.XtraForm
    {
        //private List<GuideArrangeEntity> _GuideArrangeEntities;
        private DataTable _dtGuideArrangeData;
        //string[] _providerNameAndID = BaseInfoCtrl.GetProviderNameAndID(Thread.CurrentPrincipal.Identity.Name);

        public GuideArrangeForm(DateTime dateTime)
        {
            InitializeComponent();

            dateMonth.DateTime = dateTime;
        }

        private void GuidArrangeForm_Load(object sender, EventArgs e)
        {
            //初始化语言下拉列表
            foreach (DataRow dr in BaseInfoCtrl.GetCiceroniLanguageData().Rows)
                tbLanguage.Properties.Items.Add(dr[0]);

            //初始化城市下拉列表
            tbCity.Properties.DataSource = BaseInfoCtrl.GetCityData();
            
            //初始化时间下拉列表
            upTeamDate.DateTime = dateMonth.DateTime;
            upTeamTime.Time = DateTime.Now;
            downTeamDate.DateTime = dateMonth.DateTime;
            downTeamTime.Time = DateTime.Now;

            //初始化团下拉列表
            DataSet ds = TeamGroupCtrl.GetAllIDForTeamGroup(ApplicationHelper.CurrentLoginProviderNameAndID[1]);//TeamGroupCtrl.GetAllIDForTeamGroup();
            if (ds.Tables.Count > 0)
                foreach (DataRow dr in ds.Tables[0].Rows)
                    btnTeamGroupID.Properties.Items.Add(dr["TourGroupID"].ToString().Trim());

            btnRefresh.PerformClick();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            string tourgroupId="";
            if (teamGridView.FocusedRowHandle >= 0)
            {
                //保存团行数据的团号字段
                tourgroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();

                //重新获取团数据并显示
                teamGridControl.DataSource = TeamGroupCtrl.GetTeamGroupData(btnTeamGroupID.Text, dateMonth.DateTime.ToString("yyyy-MM-dd"),ApplicationHelper.CurrentLoginProviderNameAndID[1]);//startDate,endDate);

                //存在之前选中的团行数据
                for (int i = 0; i < teamGridView.DataRowCount; i++)
                    if (tourgroupId == teamGridView.GetRowCellDisplayText(i, "TourgroupID"))
                        teamGridView.FocusedRowHandle = i;
            }
            else
            {
                teamGridControl.DataSource = TeamGroupCtrl.GetTeamGroupData(btnTeamGroupID.Text, dateMonth.DateTime.ToString("yyyy-MM-dd"), ApplicationHelper.CurrentLoginProviderNameAndID[1]);//startDate,endDate);
                if (teamGridView.FocusedRowHandle < 0)
                    LoadScheduleData("", "", "");
                else
                {
                    tourgroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();
                    string startDate = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "StartDate").ToString();
                    string endDate = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "EndDate").ToString();

                    LoadScheduleData(tourgroupId, startDate, endDate);
                }
            }
        }
        private void LoadScheduleData(string tourgroupId, string startDate, string endDate)
        {
            if (tourgroupId == "")
            {
                //scheduleGridControl.DataSource = null;

                tbRemark.Text = "";

                btnAddGuide.Enabled = false;
                btnRemoveGuide.Enabled = false;

                guideArrangeGridControl.DataSource = null;

            }
            else
            {
                //scheduleGridControl.DataSource = TeamGroupCtrl.GetTourGroupSchedule(tourgroupId).Tables[0];

                //更新备注
                tbRemark.Text = TeamGroupCtrl.GetTourGroupScheduleRemark(tourgroupId);

                //审核状态后不能'增加'、'移除'导游
                TeamStateEnum state = TeamGroupCtrl.GetTourGroupState(tourgroupId);
                if (state == TeamStateEnum.审核 || state == TeamStateEnum.终结)
                {
                    btnAddGuide.Enabled = false;
                    btnRemoveGuide.Enabled = false;
                }
                else
                {
                    btnAddGuide.Enabled = true;
                    btnRemoveGuide.Enabled = true;
                }
                //获取团计划的入境和离境的日期与时间，分别赋值到“导游筛选”条件中
                string[,] dateTimes = TeamGroupCtrl.GetScheduleDateTimeForTourGroupID(tourgroupId);

                upTeamDate.DateTime = dateTimes[0, 0] == "" ? DateTime.Parse(startDate) : DateTime.Parse(dateTimes[0, 0]);
                upTeamTime.Time = dateTimes[0, 1] == "" ? DateTime.Now : DateTime.Parse(dateTimes[0, 1]);

                downTeamDate.DateTime = dateTimes[1, 0] == "" ? DateTime.Parse(endDate) : DateTime.Parse(dateTimes[1, 0]);
                downTeamTime.Time = dateTimes[1, 1] == "" ? DateTime.Now : DateTime.Parse(dateTimes[1, 1]);

                LoadGuideArrangeDataForTourgroup(tourgroupId);
            }
        }

        private void teamGridView_DataSourceChanged(object sender, EventArgs e)
        {
            teamGridView_FocusedRowChanged(sender, new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs(0, teamGridView.FocusedRowHandle));
        }
        private void teamGridView_ColumnFilterChanged(object sender, EventArgs e)
        {
            teamGridView_FocusedRowChanged(sender, new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs(0, teamGridView.FocusedRowHandle));
        }

        private void teamGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0) return;
            if (e.FocusedRowHandle == 0)   //考虑由“ColumnFilterChanged”事件激发时，添加参数时焦点行为零的情况不符合属实际(控件获取当前焦点不准？)，因此需特殊处理
                if (((DataTable)teamGridControl.DataSource).Rows.Count == 0) return;

            //获取对应团的行程计划信息
            string tourgroupId = teamGridView.GetRowCellValue(e.FocusedRowHandle, "TourgroupID").ToString();
            string startDate = teamGridView.GetRowCellValue(e.FocusedRowHandle, "StartDate").ToString();
            string endDate = teamGridView.GetRowCellValue(e.FocusedRowHandle, "EndDate").ToString();

            LoadScheduleData( tourgroupId,  startDate,  endDate);
            
        }

        private void LoadGuideArrangeDataForTourgroup(string tourgroupId)
        {
            //获取导游安排信息
            _dtGuideArrangeData = GuideArrangeCtrl.GetGuideArrangeData(tourgroupId);
            _dtGuideArrangeData.ColumnChanged += new DataColumnChangeEventHandler(GuideArrangeData_ColumnChanged);
            guideArrangeGridControl.DataSource = _dtGuideArrangeData;
        }

        void GuideArrangeData_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            GuideArrangeEntity entity = new GuideArrangeEntity();
            entity.GuideArrangeID = int.Parse(e.Row["GuideArrangeID"].ToString());
            entity.Remark = e.Row["Remark"].ToString();
            entity.StartDate = e.Row["StartDate"].ToString();
            entity.EndDate = e.Row["EndDate"].ToString(); 
            entity.Notified = false;//bool.Parse(e.Row["Notified"].ToString());//字段隐藏了(日后确认不用可以删除)，通知字段在导游通知界面中打钩自动保存
            entity.IsAccompany = bool.Parse(e.Row["IsAccompany"].ToString());

            GuideArrangeCtrl.UpdateGuideArrangeData(entity);
        }

        private void btnGuideRefresh_Click(object sender, EventArgs e)
        {
            DateTime start = new DateTime(upTeamDate.DateTime.Year, upTeamDate.DateTime.Month, upTeamDate.DateTime.Day, upTeamTime.Time.Hour, upTeamTime.Time.Minute, 0);
            DateTime end = new DateTime(downTeamDate.DateTime.Year, downTeamDate.DateTime.Month, downTeamDate.DateTime.Day, downTeamTime.Time.Hour, downTeamTime.Time.Minute, 0);
            int statusIndex = guideArrangeStatus.SelectedIndex;

            guideGridControl.DataSource = GuideArrangeCtrl.GetGuideArrangeData(tbCity.Text,tbLanguage.Text,statusIndex,start,end,ApplicationHelper.CurrentLoginProviderNameAndID[1]);
        }

        private void btnAddGuide_Click(object sender, EventArgs e)
        {
            if (teamGridView.FocusedRowHandle < 0) return;

            List<GuideArrangeEntity> entities = new List<GuideArrangeEntity>();
            string tourgroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();

            GuideArrangeEntity entity = new GuideArrangeEntity();
            entity.Calendars = "";
            entity.CiceroniName = guideGridView.GetRowCellValue(guideGridView.FocusedRowHandle, "CiceroniName").ToString();//获取指定行的第一列导游‘姓名’
            entity.CiceroniID = int.Parse(guideGridView.GetRowCellValue(guideGridView.FocusedRowHandle, "CiceroniID").ToString());
            entity.TourgroupID = tourgroupId;
            entity.StartDate = new DateTime(upTeamDate.DateTime.Year, upTeamDate.DateTime.Month, upTeamDate.DateTime.Day, upTeamTime.Time.Hour, upTeamTime.Time.Minute, 0).ToString("yyyy-MM-dd HH:mm");
            entity.EndDate = new DateTime(downTeamDate.DateTime.Year, downTeamDate.DateTime.Month, downTeamDate.DateTime.Day, downTeamTime.Time.Hour, downTeamTime.Time.Minute, 0).ToString("yyyy-MM-dd HH:mm");
            entity.Notified = false;
            entity.IsAccompany = false;
            entity.HasEvent = 0;//0代表无事件,1代表事件信息，5代表紧急事件
            entity.Remark = "";// scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "DestinationCity").ToString() + "上团";
            entity.OwnerProviderID = ApplicationHelper.CurrentLoginProviderNameAndID[1];
            entities.Add(entity);
            GuideArrangeCtrl.CreateGuideArrangeData(entities);

            //删除guideGridView中的导游信息(刷新导游信息)
            guideGridView.DeleteRow(guideGridView.FocusedRowHandle);

            //刷新导游安排GrideView（刷新导游安排信息）
            LoadGuideArrangeDataForTourgroup(tourgroupId);

            //更新团表中的全陪信息，必须在上一行更新后(要用到最新的数据源)
            UpdateTourgroupAccompanyNames(tourgroupId);

            //刷新团列表
            btnRefresh.PerformClick();

        }

        private void btnRemoveGuide_Click(object sender, EventArgs e)
        {
            if (guideArrangeGridView.FocusedRowHandle < 0) return;

            if (MessageBox.Show("确定移除选择的导游安排信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string guideArrangeId = guideArrangeGridView.GetRowCellValue(guideArrangeGridView.FocusedRowHandle, "GuideArrangeID").ToString();
                GuideArrangeCtrl.DeleteGuideArrangeData(guideArrangeId);

                //刷新导游安排GrideView
                string tourgroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();
                LoadGuideArrangeDataForTourgroup(tourgroupId);

                //更新团表中的全陪信息，必须在上一行更新后(要用到最新的数据源)
                UpdateTourgroupAccompanyNames(tourgroupId);

                //刷新导游信息
                btnGuideRefresh.PerformClick();
                
                //刷新团列表
                btnRefresh.PerformClick();
            }
        }
        private void UpdateTourgroupAccompanyNames(string tourgroupId)
        {
            StringBuilder AccompanyNames = new StringBuilder();

            if (_dtGuideArrangeData.Rows.Count > 0)
            AccompanyNames.AppendFormat("{0}", _dtGuideArrangeData.Rows[0]["CiceroniName"]);
            if (_dtGuideArrangeData.Rows.Count > 1)
                for (int i = 1; i < _dtGuideArrangeData.Rows.Count; i++)
                    AccompanyNames.AppendFormat("|{0}", _dtGuideArrangeData.Rows[i]["CiceroniName"]);

            TeamGroupCtrl.UpdateTourGroupAccompanyNames(tourgroupId, AccompanyNames.ToString());
        }
        private void guideGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Clicks == 2)
                btnAddGuide.PerformClick();
        }

        private void GuideArrangeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //不管是否焦点在guideGridView上都将焦点移到刷新按钮上，以激发数据更改保存
            btnGuideRefresh.Focus();
        }

        //private void teamGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        //{
        //    string tourgroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();
        //    //获取备注信息
        //    tbRemark.Text = TeamGroupCtrl.GetTourGroupScheduleRemark(tourgroupId);
        //}

    }
}
